package org.shj.springcloud.zuul.controller;

import java.util.Map;

import org.shj.springcloud.zuul.pojo.User;
import org.shj.springcloud.zuul.service.AggregationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import rx.Observable;
import rx.Observer;

import com.google.common.collect.Maps;

@RestController
public class AggregationController {

	private static final Logger LOG = LoggerFactory.getLogger(AggregationController.class);
	
	@Autowired
	private AggregationService aggregationService;
	
	@GetMapping("/aggregate/{id}")
	public DeferredResult<Map<String, User>> aggregate(@PathVariable String id){
		Observable<Map<String, User>> result = this.aggregateObservable(id);
		return this.toDeferredResult(result);
	}
	
	public Observable<Map<String, User>> aggregateObservable(String id){
		return Observable.zip(
				this.aggregationService.getUserById(id),
				this.aggregationService.getMovieUserByUserId(id),
				(user, movieUser) -> {
					Map<String, User> map = Maps.newHashMap();
					map.put("user", user);
					map.put("movieUser", movieUser);
					return map;
				});
	}
	
	public DeferredResult<Map<String, User>> toDeferredResult(Observable<Map<String, User>> details){
		DeferredResult<Map<String, User>> result = new DeferredResult<>();
		details.subscribe(new Observer<Map<String, User>>(){
			public void onCompleted(){
				LOG.info("完成");
			}

			@Override
			public void onError(Throwable e) {
				LOG.error("发生错误...", e);
			}

			@Override
			public void onNext(Map<String, User> t) {
				result.setResult(t);
			}
			
		});
		return result;
	}
}
